type BodyType = Document | XMLHttpRequestBodyInit | null;

//定义参数处理接口 参数为任意类型可选的data 返回类型为BodyType
interface DataHandle{
    (data?: any): BodyType; 
}

export class ContentType{
    public name: string;
    public  dataHandle: DataHandle;//处理数据的方法

    constructor(name:string,dataHandle:DataHandle){
        this.name = name;
        this.dataHandle = dataHandle;
    }

    //这里提前将ContentType构建好,方便后面使用
    static APPLICATION_JSON: ContentType = new ContentType("application/json",(data?: any): string=>{
        if(data == undefined){
            return "{}";
        }
        return JSON.stringify(data);
    });

    //encodeURIComponent将特殊字符转译 比如& = 
    static APPLICATION_URLENCODED: ContentType = new ContentType("application/x-www-form-urlencoded",(data?: any): BodyType=>{
        if(data == undefined){
            return "";
        }
        //判断用户传递的参数是不是对象类型,如果是则循环将所有属性拼接成 a=1&b=2这种类型  
        //首先要先将data对象里的每一对属性拼接成用=的字符串,然后添加到parmArray数组里,最后将数组使用&拼接在一起就好了.
        var parmArray = [];
        if(data instanceof Object){
            for (const key in data) {
                // 如果对象的属性值直接是字符串则用这种方式直接拼接
                //如果对象的属性值是一个数组则需要拼接成 key[]=数组的第一个值 key[]=数组的第二个值
                if(!(data[key] instanceof Array)){
                    parmArray.push(`${encodeURIComponent(key)}=${encodeURIComponent(data[key])}`);
                }else{
                    for (const index in data[key]) {
                        parmArray.push(`${encodeURIComponent(key)}[]=${encodeURIComponent(data[key][index])}`);
                    }
                }
            }
        }
        return parmArray.join("&").replace(/%20/g, "+");
    })

    static MULTIPART_FORM_DATA: ContentType = new ContentType("multipart/form-data",(data?: any): FormData=>{
        let fd = new FormData();

        if(data == undefined){
            return fd;
        }

        if(data instanceof Object){
            for (const key in data) {
                fd.append(key,data[key]);
            }
        }
        return fd;
    });
}